package ai.plantdata.service.impl;

import ai.plantdata.dao.strategy.RelationHandle;
import ai.plantdata.dao.strategy.SeparateHandle;
import ai.plantdata.graph.mongo.MongoGraphStore;
import ai.plantdata.graph.mongo.util.GlobalUtils;
import ai.plantdata.service.WriteService;
import ai.plantdata.util.SeparateStrategyUtils;
import ai.plantdata.vo.AssociationTable;
import ai.plantdata.vo.DataSourceConfig;
import ai.plantdata.vo.SchemalVO;
import ai.plantdata.vo.SeparateTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: WangHui
 * @Date: 2021/7/9 10:27
 * @Description:
 */
@Service
public class WriteServiceImpl implements WriteService {

    @Autowired
    private RelationHandle relationHandle;

    static MongoGraphStore store = null;

    @Async
    @Override
    public void createSchemal(String kgName, SchemalVO schemalVO) {
        store = new MongoGraphStore(kgName);
        GlobalUtils.removeLock(kgName);
        store.start();
        DataSourceConfig dataSourceConfig = schemalVO.getDataSourceConfig();
        List<SeparateTable> separateTables = schemalVO.getSeparateTables();
        Map<String, SeparateTable> map = new HashMap<>();
        for (SeparateTable separateTable : separateTables) {
            map.put(separateTable.getTableName(), separateTable);
        }
        for (SeparateTable separateTable : separateTables) {
            separateTable.setMap(map);
            SeparateHandle select = SeparateStrategyUtils.select(separateTable.getStatus());
            select.schemaHandle(separateTable, dataSourceConfig, store);
        }
        List<AssociationTable> associationTables = schemalVO.getAssociationTables();
        for (AssociationTable associationTable : associationTables) {
            relationHandle.schemaHandle(associationTable, dataSourceConfig, map, store);
        }
        store.finish();
    }

    @Async
    @Override
    public void createNode(String kgName, SchemalVO schemalVO) {
        createSchemal(kgName, schemalVO);
        store = new MongoGraphStore(kgName);
        GlobalUtils.removeLock(kgName);
        store.start();
        DataSourceConfig dataSourceConfig = schemalVO.getDataSourceConfig();
        List<SeparateTable> separateTables = schemalVO.getSeparateTables();
        for (SeparateTable separateTable : separateTables) {
            SeparateHandle select = SeparateStrategyUtils.select(separateTable.getStatus());
            select.entityHandle(separateTable, dataSourceConfig, store);
        }
        List<AssociationTable> associationTables = schemalVO.getAssociationTables();
        for (AssociationTable associationTable : associationTables) {
            relationHandle.entityHandle(associationTable, dataSourceConfig, store);
        }
        store.finish();
    }
}
